import {Injectable} from '@angular/core';
import {Storage} from '@ionic/storage';
import {ActionSheetController} from 'ionic-angular';
import {Camera, CameraOptions} from '@ionic-native/camera';
import {HttpService} from 'http-service';
// import {ReloadingController} from '../components/reloading/reloading-controller';

// export interface Attachment {
//   bigPicId?: string;
//   thumbnailId?: string;
//   thumbnail?: string;
//   bigPic?: string;

// }

@Injectable()
export class UploadPhotoService {
  loader: any;

  constructor(
              // private loadingCtrl: ReloadingController,
              private camera: Camera,
              private actionSheetCtrl: ActionSheetController
              // private storage: Storage,
              // private http: HttpService
            ) {
  }

  // private presentLoading(tipMessage: string = '') {
  //   tipMessage = tipMessage || '正在上传图片...';
  //   this.loader = this.loadingCtrl.create({
  //     content: tipMessage
  //   });
  //   this.loader.present();
  // }

  // private closeLoading() {
  //   if (this.loader) {
  //     this.loader.dismiss();
  //     this.loader = null;
  //   }
  // }

  /**
   * pick or take a photo use carma and the upload to file server
   * @param onPreUploadImage hocks on image pre upload
   * @returns {Promise<any>}
   * { state: 1,data: { serveResponse: {  attachmentId:''，thumbnailId:''},srcImg: base64ImageData}}
   */
 
  public pickOrTakePhoto() {
    return new Promise((resolve) => {
      const actionSheet = this.actionSheetCtrl.create({
        title: '',
        buttons: [
          {
            text: '从相册选择照片',
            handler: () => {
              const options: CameraOptions = {
                quality: 50,
                destinationType: this.camera.DestinationType.FILE_URI,
                sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
                mediaType: this.camera.MediaType.PICTURE,
                allowEdit: false,
                correctOrientation: true,
                encodingType: this.camera.EncodingType.JPEG,
                targetWidth: 750,
                targetHeight: 1334
              };
              this.camera.getPicture(options).then((path) => {
                resolve(path);
                // if (onPreUploadImage) {
                //   onPreUploadImage();
                // }
                // // this.presentLoading();
                // this.uploadImageFile(imageData).then((response) => {
                //   // this.closeLoading();
                //   if (response) {
                //     resolve({
                //       state: 1,
                //       data: response
                //     });
                //   } else {
                //     resolve({
                //       state: 0,
                //       data: null
                //     });
                //   }
                // });
              }, (err) => {
                // this.closeLoading();
                resolve(null);
              });
            }
          }, {
            text: '拍照',
            handler: () => {
              const options: CameraOptions = {
                quality: 50,
                destinationType: this.camera.DestinationType.DATA_URL,
                sourceType: this.camera.PictureSourceType.CAMERA,
                encodingType: this.camera.EncodingType.JPEG,
                mediaType: this.camera.MediaType.PICTURE,
                allowEdit: false,
                correctOrientation: true
              };
              // this.uploadImageFile(imageData).then((response) => {
              //     // this.closeLoading();
              //     if (response) {
              //       resolve({
              //         state: 1,
              //         data: response
              //       });
              //     } else {
              //       resolve({
              //         state: 0,
              //         data: null
              //       });
              //     }
              //   });
              this.camera.getPicture(options).then((path) => {
                // this.presentLoading();
                resolve(path);
              }, (err) => {

                // this.closeLoading();
                resolve(null);
              });
            }
          }, {
            text: '取消',
            role: 'cancel',
            handler: () => {
              resolve(null);
            }
          }
        ]
      });
      actionSheet.present();
    });
  }

  // /**
  //  *  uplaod image to server
  //  * @param base64ImageData
  //  * @returns {Promise<any>}
  //  */
  // tslint:disable-next-line:member-ordering
  // public uploadImageFile(url) {
  //   // base64ImageData = 'data:image/jpeg;base64,' + base64ImageData;
  //   const body = {
  //     attachmentBase64: [base64ImageData]
  //   };
  //   return new Promise(((resolve) => {
  //     this.http.post("url", body)
  //       .subscribe((data) => {
  //         const response = data.json();
  //         if (response['code'] === 200) {
  //           const respAttachmentArray = response['data'] || [];
  //           if (respAttachmentArray.length > 0) {
  //             this.addImageCache(respAttachmentArray[0].attachmentId, base64ImageData).then();
  //           }
  //           resolve({
  //             serveResponse: respAttachmentArray[0],
  //             srcImg: base64ImageData
  //           });
  //         } else {
  //           resolve(null);
  //         }
  //       }, (err) => {
  //         resolve(null);
  //       });
  //   }));
  // }

  // /**
  //  * if find in local storage then use cache .otherwise download from server
  //  * @param {string} imgId
  //  * @returns {Promise<string>} the image date(base64 encoded)
  //  */
  // tslint:disable-next-line:member-ordering
  // public getImage(imgId: string): Promise<string> {
  //   return new Promise((resolve) => {
  //     if (imgId) {
  //       this.storage.get('CACHED_IMAGE:' + imgId).then((dataFromLocal) => {
  //         if (dataFromLocal) {
  //           resolve(dataFromLocal);
  //         } else {
  //           this.downloadImageFile(imgId).then((dataFromServer) => {
  //             resolve(dataFromServer);
  //           });
  //         }
  //       });
  //     } else {
  //       resolve(null);
  //     }
  //   });
  // }

  // private addImageCache(id: string, base64ImageData: string) {
  //   return this.storage.set('CACHED_IMAGE:' + id, base64ImageData);
  // }

  // private downloadImageFile(attachmentId: string) {
  //   return new Promise<string>((resolve) => {
  //     this.http.get("url" + attachmentId)
  //       .subscribe((data) => {
  //         const response = data.json();
  //         if (response['code'] === 200) {
  //           const dataImage = 'data:image/jpeg;base64,' + response['data'].attachment;
  //           this.addImageCache(attachmentId, dataImage);
  //           resolve(dataImage);
  //         } else {
  //           resolve('assets/img/no_image.png');
  //         }
  //       }, (err) => {
  //         resolve('assets/img/no_image.png');
  //       });
  //   });
  // }

  // tslint:disable-next-line:member-ordering
  // public initAttachmentArray(bigPicIds: string, thumbnailIds: string): Array<Attachment> {
  //   const picIdArray = bigPicIds ? bigPicIds.split(',') : [];
  //   const thumbnailIdArray = thumbnailIds ? thumbnailIds.split(',') : [];
  //   const attachmentArray: Array<Attachment> = [];
  //   for (let i = 0; i < picIdArray.length; i++) {
  //     const attachment: Attachment = {};
  //     attachment.bigPicId = picIdArray[i];
  //     attachment.bigPic = '';
  //     attachment.thumbnail = '/assets/img/loading.gif';
  //     attachment.thumbnailId = thumbnailIdArray[i];
  //     attachmentArray.push(attachment);
  //   }
  //   return attachmentArray;
  // }

  // tslint:disable-next-line:member-ordering
  // public wrapAttachmentThumbnail(attachmentArray: Array<Attachment>) {
  //   if (!attachmentArray) {
  //     return;
  //   }
  //   for (const obj of attachmentArray) {
  //     this.downloadImageFile(obj.thumbnailId).then((imageThumbnail) => {
  //       if (imageThumbnail) {
  //         obj.thumbnail = imageThumbnail;
  //       }
  //     });
  //   }
  // }
}
